<?php
/**
 * Created by PhpStorm.
 * User: kinso
 * Date: 2017/1/3
 * Time: 下午2:19
 */

namespace common\queue;


use yii\redis\Connection;

class RedisQueue extends Connection implements QueueInterface
{

    /**
     * 往队列添加元素
     *
     * @param mixed $members
     * @param string $queue
     * @return string
     */
    public function push($members, $queue)
    {
        if (empty($queue) || !is_string($queue) || empty($members)) {
            return 0;
        }
        $params = [$queue];
        if (is_array($members)) {
            foreach ($members as $member) {
                $params[] = json_encode($member, JSON_UNESCAPED_UNICODE);
            }
        } else {
            $params[] = json_encode($members, JSON_UNESCAPED_UNICODE);
        }
        return (int)$this->executeCommand('LPUSH', $params);
    }

    /**
     * 从队列弹出元素
     *
     * @param string $queue
     * @return string|false
     */
    public function pop($queue)
    {
        if (empty($queue) || !is_string($queue)) {
            return '';
        }
        $params = [$queue];
        $result = $this->executeCommand('RPOP', $params);
        return strval($result);
    }

    /**
     * 从队列阻塞弹出元素
     * @param $queue
     * @return string
     * @throws \yii\db\Exception
     */
    public function bpop($queue)
    {
        if (empty($queue) || !is_string($queue)) {
            return '';
        }
        $params = [$queue, 0];
        $result = $this->executeCommand('BRPOP', $params);
        return strval($result);
    }

    /**
     * @param $queue
     * @return mixed
     */
    public function count($queue)
    {
        if(!$queue){
            return 0;
        }
        return (int) $this->executeCommand('LLEN',[$queue]);
    }

}